import 'package:flutter/material.dart';
import 'package:syria_sports/core/app_export.dart';
import 'package:syria_sports/data/controllers/users_controller.dart';
import 'dart:io';



import '../../../../data/models/auth/user.dart';

part 'add_subscription_requests_state.dart';

class AddSubscriptionRequestsCubit extends Cubit<AddSubscriptionRequestsState> {
  TextEditingController fullNameController = TextEditingController();
  TextEditingController barcodeController = TextEditingController();
  TextEditingController birthdateController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController emailController = TextEditingController();
  TextEditingController descriptionController = TextEditingController();

  final FocusNode fullNameFocusNode = FocusNode();
  final FocusNode barcodeFocusNode = FocusNode();
  final FocusNode birthdateFocusNode = FocusNode();
  final FocusNode passwordFocusNode = FocusNode();
  final FocusNode phoneFocusNode = FocusNode();
  final FocusNode emailFocusNode = FocusNode();
  final FocusNode descriptionFocusNode = FocusNode();



  late String barcode;
  bool editMode = false;
  late String userId;

  AddSubscriptionRequestsCubit() : super(AddSubscriptionRequestsInitial());

  static AddSubscriptionRequestsCubit get(context) => BlocProvider.of(context);
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  File? image;
  String? imageURL;
  int gender = 0;


  void init(User? user) {
    if(user!=null){
      userId = user.userId!;
      editMode = true;
      fullNameController.text = user.fullName ?? '';
      barcodeController.text = user.barcode ?? '';
      birthdateController.text = user.birthdate ?? '';
      passwordController.text = user.password ?? '';
      phoneController.text = user.phone ?? '';
      emailController.text = user.email ?? '';
      descriptionController.text = user.description ?? '';
      gender = user.genderValue == '0' ? 0 : 1;
      if(user.image != null && user.image!.isNotEmpty){
        imageURL = user.image;
      }
      emit(AddAdminUpdate());
    }else{
      editMode = false;
    }
  }

  void onChangeImage(File? image) {
    this.image = image;
    emit(AddAdminUpdate());
  }

  onScanBarcode(String barcode){
    this.barcode = barcode;
    barcodeController.text = this.barcode;
    emit(AddAdminUpdate());
  }


  clearOldData(){
     fullNameController.text = "";
     passwordController.text = "";
     barcodeController.text = "";
     phoneController.text = "";
     emailController.text = "";
     birthdateController.text = "";
     descriptionController.text = "";
     image = null;
  }

  addUser(BuildContext context)async{

    var dialogLoading =  context;
     showDialog(context: context, builder: (context1){
       dialogLoading = context1;
       return const Center(child: CircularProgressIndicator());
     });
    User user = User(
      type: 4.toString(),
      fullName: fullNameController.text.trim(),
      genderValue: gender.toString(),
      barcode: null,
      birthdate: birthdateController.text.trim(),
      password: passwordController.text.trim(),
      phone: phoneController.text.trim(),
      email: emailController.text.trim(),
      description: descriptionController.text.trim(),
    );


    emit(AddSubscriptionRequestsLoading());
    user.imageFile = image;

    await UsersController.register(user).then((value){
      print("register ${value?.state} ${!PrefUtils.isLogged()}");
      if(value?.state == true) {
        if(!PrefUtils.isLogged()){
          var user = User.fromJson(value!.data);
          PrefUtils.saveUserData(user);
          emit(AddAdminRegisterDone());
        }else {
          clearOldData();
          emit(AddSubscriptionRequestsDone());
        }
      }
    });
    Navigator.pop(dialogLoading);
  }


  updateUser(BuildContext context)async{
    var dialogLoading =  context;
    showDialog(context: context, builder: (context1){
      dialogLoading = context1;
      return const Center(child: CircularProgressIndicator());
    });
    User user = User(
      userId: userId,
      type: 4.toString(),
      fullName: fullNameController.text.trim(),
      genderValue: gender.toString(),
      barcode: barcodeController.text.trim(),
      birthdate: birthdateController.text.trim(),
      password: passwordController.text.trim(),
      phone: phoneController.text.trim(),
      email: emailController.text.trim(),
      description: descriptionController.text.trim(),
    );

    emit(AddSubscriptionRequestsLoading());
    user.imageFile = image;

    await UsersController.updateUser(user).then((value){});
    Navigator.pop(dialogLoading);
    emit(AddSubscriptionRequestsDone());
  }



  update(){
    emit(AddAdminUpdate());
  }

  Future<void> selectDate(BuildContext context) async {
    final DateTime? pickedDate = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime.now(),
      builder: (BuildContext context, Widget? child) {
        return Theme(
          data: ThemeData(
            fontFamily: 'Tajawal',
            visualDensity: VisualDensity.standard,
            colorScheme: const ColorScheme.dark().copyWith(
              primary: Colors.red, // تحديد اليوم بلون أحمر
            ),
            textButtonTheme: TextButtonThemeData(
              style: ButtonStyle(
                foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
              ),
            ),
          ),
          child: child!,
        );
      },
    );

    if (pickedDate != null) {
      String formattedDate = DateFormat('yyyy-MM-dd').format(pickedDate);
      birthdateController.text = formattedDate;
    }

    emit(AddAdminUpdate());
  }

}
